package com.example.fence.init;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.fence.Task;
import com.example.fence.enums.AlarmMode;
import com.example.fence.service.MailService;
import com.example.fence.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

import static com.example.fence.init.DeviceUtil.SNtoUUID;
import static com.example.fence.util.FenceDetectUtil.PoiInPoly;
import static com.example.fence.util.FenceStoreUtil.*;


@Component
@Slf4j
public class FenceUtil {
    @Value("${auth.username}")
    private String username;
    @Value("${auth.password}")
    private String password;
    /**
     * 项目启动时启动，获取设备列表，建立映射表
     */
    @PostConstruct
    @DependsOn("DeviceUtil")
    public void start() {
        init();
    }
    public static void init() {
        String token= HttpClientUtil.get_token("http://47.92.164.101:28080/api/auth/login","tenant@thingsboard.org","tenant")[0];
        String refreshToken=HttpClientUtil.get_token("http://47.92.164.101:28080/api/auth/login","tenant@thingsboard.org","tenant")[1];
        log.info("读取fence信息中，此过程可能比较长.........");
        for (Map.Entry<String, String> entry : SNtoUUID.entrySet()) {
            //应该还要判断无法获取到设备列表怎么办
            String url="http://47.92.164.101:28080/api/plugins/telemetry/DEVICE/"+entry.getValue()+"/values/timeseries?keys=fence,Delete,ReciveBox,SendBox,WarnType,sendInterval&useStrictDataTypes=false";
            System.out.println("start url:"+url);  // 便于本地启动看启动完了没
            String[] resultStr=HttpClientUtil.get_data(url,token);//String 格式获取结果, [0]为statusCode，[1]为结果(结果可能不是json)
            if(Integer.valueOf(resultStr[0])==200){
                //获取设备列表
                JSONObject jsonResult = JSONObject.parseObject(resultStr[1]);
                //Delete
                JSONArray dataList=jsonResult.getJSONArray("Delete");
                JSONObject fenceObject = dataList.getJSONObject(0);
                String  fenceValue = fenceObject.getString("value");
                if(fenceValue != null && fenceValue.equals("N1")) continue;
                //获取fence
                 dataList=jsonResult.getJSONArray("fence");
                 fenceObject = dataList.getJSONObject(0);
                 fenceValue = fenceObject.getString("value");
                if(fenceValue==null) continue;
                fenceValue = fenceValue.substring(2, fenceValue.length() - 1).replace(" ","");
                String[] arr = fenceValue.split(",");
                List<String> list = new ArrayList<>();
                for (int i = 0; i < arr.length; i += 2) {
                    list.add(arr[i] + "," + arr[i+1]);
                }
                imeiToPointList.put(entry.getKey(),list) ;
                //ReciveBox
                dataList=jsonResult.getJSONArray("ReciveBox");
                fenceObject = dataList.getJSONObject(0);
                fenceValue = fenceObject.getString("value");
                if(fenceValue==null) continue;
                String[] emailArray = fenceObject.getString("value").substring(2, fenceValue.length() - 1).replace(" ","").split(",");
                Set<String> emailSet = new HashSet<>();
                for (String email : emailArray) {
                    emailSet.add(email);
                }
                deviceReceiveEmail.put(entry.getKey(),emailSet);
                //SendBox
                dataList=jsonResult.getJSONArray("SendBox");
                fenceObject = dataList.getJSONObject(0);
                fenceValue = fenceObject.getString("value");
                if(fenceValue==null) continue;
                fenceValue = Arrays.toString(fenceValue.substring(1, fenceValue.length()).replace(" ","").split(","));
                deviceSendEmail.put(entry.getKey(),fenceValue);
                //WarnType
                dataList=jsonResult.getJSONArray("WarnType");
                fenceObject = dataList.getJSONObject(0);
                fenceValue = fenceObject.getString("value");
                if(fenceValue==null) continue;
                String[] WarnArray = fenceObject.getString("value").substring(2, fenceValue.length() - 1).replace(" ","").split(",");
                Set<Integer> WarnSet = new HashSet<>();
                for (String warn : WarnArray) {
                    WarnSet.add(Integer.valueOf(warn));
                }
                deviceAlarmMode.put(entry.getKey(),WarnSet);
                //sendInterval
                dataList=jsonResult.getJSONArray("sendInterval");
                fenceObject = dataList.getJSONObject(0);
                fenceValue = fenceObject.getString("value");
                if(fenceValue==null) continue;
                int Interval=Integer.valueOf(fenceValue.substring(1, fenceValue.length())) ;
                sendInterval.put(entry.getKey(),Interval);


            }
            else{
                log.info("SNtoUUID error"+Integer.valueOf(resultStr[0]));
            }
        }
        for (Map.Entry<String, List<String>> entry : imeiToPointList.entrySet()) {
            String key = entry.getKey();
            List<String> values = entry.getValue();
            // 处理键值对
            log.info(key+values);
        }
        for (Map.Entry<String, Boolean> entry : imeiLock.entrySet()) {
            String key = entry.getKey();
            Boolean values = entry.getValue();
            // 处理键值对
            log.info(key+values);
        }
        for (Map.Entry<String, Set<Integer>> entry : deviceAlarmMode.entrySet()) {
            String key = entry.getKey();
            Set<Integer> values = entry.getValue();
            // 处理键值对
            log.info(key+values);
        }
        log.info("初始化完成！");
    }
    public  static void main(String[] args) throws Exception {
        String token= HttpClientUtil.get_token("http://47.92.164.101:28080/api/auth/login","tenant@thingsboard.org","tenant")[0];
        String refreshToken=HttpClientUtil.get_token("http://47.92.164.101:28080/api/auth/login","tenant@thingsboard.org","tenant")[1];
            String url="http://47.92.164.101:28080/api/plugins/telemetry/DEVICE/efb600f0-6685-11ee-abb8-e960d73f3051/values/timeseries?keys=fence,ReciveBox,SendBox,WarnType&useStrictDataTypes=false";
            String[] resultStr=HttpClientUtil.get_data(url,token);//String 格式获取结果, [0]为statusCode，[1]为结果(结果可能不是json)
            if(Integer.valueOf(resultStr[0])==200){
                //获取设备列表
                JSONObject jsonResult = JSONObject.parseObject(resultStr[1]);
                //获取fence
                JSONArray dataList=jsonResult.getJSONArray("fence");
                JSONObject fenceObject = dataList.getJSONObject(0);
                String fenceValue = fenceObject.getString("value");
                fenceValue = fenceValue.substring(2, fenceValue.length() - 1).replace(" ","");

                imeiToPointList.put("869523057004187", Collections.singletonList(fenceValue)) ;
                System.out.println(Collections.singletonList(fenceValue));
                System.out.println(PoiInPoly(Collections.singletonList(fenceValue), "120.215909, 30.254806"));
                //ReciveBox
                dataList=jsonResult.getJSONArray("ReciveBox");
                fenceObject = dataList.getJSONObject(0);
                fenceValue = fenceObject.getString("value");
                String[] emailArray = fenceValue.substring(2, fenceValue.length() - 1).replace(" ","").split(",");
                Set<String> emailSet = new HashSet<>();
                Collections.addAll(emailSet, emailArray);
                deviceReceiveEmail.put("869523057004187",emailSet);
                System.out.println(deviceReceiveEmail.get("869523057004187"));
                //SendBox
                dataList=jsonResult.getJSONArray("SendBox");
                fenceObject = dataList.getJSONObject(0);
                fenceValue = fenceObject.getString("value");
                fenceValue = Arrays.toString(fenceValue.substring(1, fenceValue.length()).replace(" ","").split(","));
                deviceSendEmail.put("869523057004187",fenceValue);
                System.out.println(deviceSendEmail.get("869523057004187"));
                //WarnType
                dataList=jsonResult.getJSONArray("WarnType");
                fenceObject = dataList.getJSONObject(0);
                fenceValue = fenceObject.getString("value");
                String[] WarnArray = fenceObject.getString("value").substring(2, fenceValue.length() - 1).replace(" ","").split(",");
                Set<Integer> WarnSet = new HashSet<>();
                for (String warn : WarnArray) {
                    WarnSet.add(Integer.valueOf(warn));
                }
                deviceAlarmMode.put("869523057004187",WarnSet);
                System.out.println(deviceAlarmMode.get("869523057004187"));
                String IMEI="869523057004187";

                if(true){
                    if(!deviceAlarmMode.containsKey(IMEI)){
                        return;
                    }
                    Set<Integer> alarmModes = deviceAlarmMode.get(IMEI);
                    //设备出fence后警告的类型 默认断电+发邮件
                    for(Integer num : alarmModes) {
                        AlarmMode alarmMode=AlarmMode.values()[num];
                        switch (alarmMode){
                            case EMAIL:
                                String lat="123";
                                String lon="123";
                                System.out.println("1");
                                break;
                            case LOCK:
                                //Task.PostC2("1/1/1");
                                System.out.println("2");
                                break;
                            default:
                                log.error("deviceAlarmMode 不正确,IMEI:{}",IMEI);
                                break;
                        }
                    }

                }

            }
            else{
                log.info("SNtoUUID error"+Integer.valueOf(resultStr[0]));
            }

    }
}
